package com.cjt.chat.controller;

import com.cjt.chat.pojo.Message;
import com.cjt.chat.pojo.User;
import com.cjt.chat.service.UserService;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;

/**
 * @author cjt
 * @since 2024/3/29
 */
@RestController
@RequestMapping(path = "/upload")
public class UploadController {
    @Resource
    private UserService userService;

    @PostMapping(path = "/headImage")
    public Message setHeadImage(MultipartFile headImage, HttpServletRequest request, HttpSession session) throws IOException {
        Message message = new Message();
        User user = (User) session.getAttribute("user");
        if (headImage.getSize() > (1024 * 1024) || user == null) {
            message.setMessageType("warning");
            message.setFrom(0);
            message.setMessage("上传失败!");
            return message;
        }


        String originalFilename = headImage.getOriginalFilename();

        String fileName = user.getUserid() + "." + originalFilename.substring(originalFilename.lastIndexOf(".") + 1);

        //String path = this.getClass().getResource("/static/").getPath();
        String path = System.getProperty("user.dir") + "/static/";


        //将旧的头像文件删除
        String oldHeadImage = user.getHeadImage();
        String[] split = oldHeadImage.split("/");
        String oldHeadImageFileName = split[split.length - 1];
        new File(path + "head-image/" + oldHeadImageFileName).delete();

        //保存新头像
        File file = new File(path + "head-image/");
        if (!file.exists()) {
            file.mkdirs();
        }
        File saveFile = new File(path + "head-image/" + fileName);

        headImage.transferTo(saveFile);

        message.setFrom(0);
        message.setMessageType("success");
        message.setMessage("上传成功!");

        String newHeadUrl = request.getContextPath() + "/static/head-image/" + fileName;
        userService.setUserHeadImage(newHeadUrl, user.getUserid());
        user.setHeadImage(newHeadUrl);

        return message;
    }
}
